<template>
  <div>
    <div @scroll="handleScroll" ref="scrollContainer" class="scroll-container">
      <div v-for="(website,index) in websites" :key="index" class="website-item">
        <el-row>
          <el-col :xs="24" :sm="6" :md="4">
            <el-image
              class="website-image"
              :src="website.sitePic.replace('dist/', '')"
              fit="cover"
            ></el-image>
          </el-col>
          <el-col :xs="24" :sm="12" :md="14">
            <div class="website-info">
              <h3>
                {{ website.siteName }}
                <el-tag
                  :style="
                    website.onlineState === 1 ? 'backgroundColor: #dcffd6' : ''
                  "
                  >{{ website.onlineState === 0 ? "未上线" : "上线" }}</el-tag
                >
              </h3>
              <div class="urlTimes">
                <a
                  :href="website.siteUrl.replace('dist/', '')"
                  target="_blank"
                  >{{ website.siteUrl }}</a
                >
                <p>创建于{{ website.createAt }}</p>
              </div>
              <div class="buttons">
                <el-button @click="editWebsite(website.id)">编辑</el-button>
                <el-button @click="viewData(website.id)">数据</el-button>
                <el-button @click="viewMessages(website.id)">留言</el-button>
                <el-button @click="settings(website.id)">设置</el-button>
              </div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="6" :md="6" class="visit-count">
            <div>
              <h2>{{ website.visits }}</h2>
              <p>过去7天访问量</p>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 底部提示 -->
    <div v-if="isBottom" class="bottom-text">已经到底啦~</div>

    <div class="loading" v-load:[loadText]="loading" />

    <el-dialog
      title="设置"
      :visible.sync="dialogFormVisible"
      @close="resetForm"
    >
      <settingDialog
        ref="settingDialog"
        :websites="selectedWebsite"
        :submitHandler="submitNewWebsite"
        :onlineStateHandler="submitOnlineState"
        @refresh="getSiteList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">取 消</el-button>
        <el-button type="primary" @click="submitDialog">确 定</el-button>
        <el-button type="danger" @click="delBtnClick">删除</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import {
  getSiteList,
  editSiteInfo,
  delSite,
  updateOnlineState,
} from "@/api/api.js";
import settingDialog from "./components/settingDialog.vue";

export default {
  name: "Launcher",
  data() {
    return {
      websites: [],
      loadText: "加载中...",
      loading: false,
      selectedWebsite: {},
      dialogFormVisible: false, // 控制子组件dialog显示隐藏
      pageNo: 1,
      pageSize: 5,
      total: 0,
      isBottom: false,
    };
  },
  created() {
    this.getSiteList();
    this.$nextTick(() => {
      document.querySelector(".el-main").style.padding = "0";
      document.querySelector(".el-main").style.overflow = "hidden";
      // 如果跳转到其他页面，销毁el-main的样式
      this.$router.beforeEach((to, from, next) => {
        if (to.name !== "网站管理") {
          document.querySelector(".el-main").style.padding = "20px";
          document.querySelector(".el-main").style.overflow = "auto";
        }
        next();
      });
    });
  },
  methods: {
    // 获取网站列表
    async getSiteList() {
      // 如果已经加载了所有数据，就不再请求
      if (this.websites.length >= this.total && this.total !== 0) return;
      try {
        this.loading = true;
        const list = await getSiteList({
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          sort: "updateAt",
          sortType: "asc",
        });
        if (list.data.code == 200) {
          this.total = list.data.result?.total;
          const websitesTemp = list.data.result?.records;
          // 给list.data.result?.records[0]添加上visits属性
          list.data.result?.records.forEach((item) => {
            item.visits = 475415;
          });
          this.websites = [...this.websites, ...websitesTemp];
        }
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }
    },
    handleScroll() {
      const container = this.$refs.scrollContainer;
      const scrollTop = container.scrollTop;
      const clientHeight = container.clientHeight;
      const scrollHeight = container.scrollHeight;

      // 判断是否到底部
      if (scrollTop + clientHeight >= scrollHeight - 1) {
        // 增加一个容差
        this.isBottom = true;
        this.pageNo++;
        this.getSiteList();
      } else {
        this.isBottom = false;
      }
    },
    // 加载html
    load(path) {
      this.loading = true;
      axios
        .get(path, {
          headers: {
            accept: "text/html;charset=UTF-8",
          },
          params: {},
        })
        .then((res) => {
          this.$store.commit("setHomepageHTML", res.data);
          this.$store.commit("triggerForceImport");
          this.$nextTick(() => {
            this.loading = false;
          });
        })
        .catch((err) => {
          console.error(err);
          this.$nextTick(() => {
            this.loading = false;
          });
        });
    },
    async editWebsite(id) {
      this.$router.push({
        name: "网站子页面列表",
        query: { id },
      });
    },
    viewData(id) {
      // 查看数据的逻辑
      this.$router.push({
        name: "数据页面",
        query: { id },
      });
    },
    viewMessages(id) {
        // 查看留言的逻辑
      this.selectedWebsite = this.websites.find((website) => website.id === id);
        console.log(id);
      this.$router.push({
        name: "留言",
        query: { id },
      });
    },
    settings(id) {
      // 找到对应 id 的 website 数据
      this.selectedWebsite = this.websites.find((website) => website.id === id);
      this.dialogFormVisible = true; // 点击设置时打开对话框
    },
    cancelDialog() {
      this.resetForm();
      this.dialogFormVisible = false;
    },
    async submitDialog() {
      await this.$refs.settingDialog.submit(); // 调用子组件的submit方法
      // 重置分页信息并清空网站列表
      this.dialogFormVisible = false;
      setTimeout(async() => {
        this.pageNo = 1;
        this.websites = [];
        await this.getSiteList(); // 重新获取数据
      }, 0);
    },
    // 用来传递给子组件进行编辑信息的接口
    async submitNewWebsite(websiteInfo) {
      return await editSiteInfo(websiteInfo);
    },
    // 用来传递给子组件进行更改上下线状态的接口
    async submitOnlineState(websiteInfo) {
      return await updateOnlineState(websiteInfo);
    },
    resetForm() {
      this.$refs.settingDialog.resetForm(); // 调用子组件的resetForm方法
    },
    delBtnClick() {
      this.$confirm("此操作将永久删除该网站, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          try {
            delSite(this.selectedWebsite.id).then((res) => {
              if (res.data.code === 200) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                // 重置分页信息并清空网站列表
                this.pageNo = 1;
                this.websites = [];
                this.getSiteList(); // 重新获取数据
                this.dialogFormVisible = false;
              } else {
                this.$message({
                  type: "error",
                  message: "删除失败!",
                });
              }
            });
          } catch (error) {
            console.error(error);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  components: {
    settingDialog,
  },
};
</script>

<style lang="scss" scoped>
/* 列表区域 */
.scroll-container {
  height: 100vh;
  overflow-y: auto;
}
.website-item {
  margin: 20px 0;
  padding: 20px;
  border-bottom: 1px solid #bebebe;
  &:last-child {
    padding-bottom: 60px;
  }
}

/* 底部提示文字样式 */
.bottom-text {
  text-align: center;
  margin-top: 20px;
  font-size: 16px;
  color: #666;
  position: relative; /* 设置相对定位 */
  bottom: 0;
}

.website-image {
  width: 100%;
  height: 100px;
}

.website-info {
  margin: 0 20px;
  .urlTimes {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    margin: 5px 5px 15px 0;
    a {
      margin-right: 10px;
      text-decoration: none;
      color: #6e5eff;
    }
    p {
      margin-top: 5px;
      color: #bdbdbd;
      font-size: 12px;
    }
  }
  .buttons {
    display: flex;
    gap: 10px;
    .el-button {
      margin-left: 0;
    }
  }
}

.visit-count {
  text-align: right;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  h2 {
    margin: 0;
    font-size: 24px;
  }
  p {
    margin: 0;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .website-image {
    width: 100%;
    height: 200px;
  }
  .website-info {
    margin: 10px 0;
  }
  .visit-count {
    margin-top: 20px;
    text-align: center;
  }
}

@media (max-width: 480px) {
  .website-info .buttons {
    flex-direction: column;
    align-items: flex-start;
  }
}

.loading {
  // 居中
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 999;
}
</style>
